import { ButtonHTMLAttributes, forwardRef, ElementType } from 'react'
import { cn } from '@/lib/utils'

interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: 'primary' | 'secondary' | 'outline' | 'ghost'
  size?: 'sm' | 'md' | 'lg'
  as?: ElementType
  href?: string
}

const Button = forwardRef<any, ButtonProps>( // 将 ref 类型设置为 any
  (
    {
      className,
      variant = 'primary',
      size = 'md',
      type = 'button',
      as: Component = 'button',
      href,
      ...props
    },
    ref
  ) => {
    const classes = cn(
      'inline-flex items-center justify-center rounded-md font-medium transition-colors',
      'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2',
      'disabled:pointer-events-none disabled:opacity-50',
      {
        'bg-primary-600 text-white hover:bg-primary-700': variant === 'primary',
        'bg-gray-100 text-gray-900 hover:bg-gray-200': variant === 'secondary',
        'border border-gray-300 bg-transparent hover:bg-gray-100': variant === 'outline',
        'hover:bg-gray-100': variant === 'ghost',
        'h-8 px-3 text-sm': size === 'sm',
        'h-10 px-4': size === 'md',
        'h-12 px-6 text-lg': size === 'lg',
      },
      className
    )

    const componentProps: any = { ref, className: classes, ...props }

    if (Component === 'button') {
      componentProps.type = type
    }

    if (href) {
      componentProps.href = href
    }

    // 显式将 Component 转换为 React.ComponentType<any>
    const RenderComponent = Component as React.ComponentType<any>;
    return <RenderComponent {...componentProps} />
  }
)

Button.displayName = 'Button'

export default Button 